import { Controller } from 'egg';

export default class RoleRightsController extends Controller {
  // 给角色分配权限接口
  public async create() {
    const { ctx } = this;
    const data = ctx.request.body;
    const { roleId, rightsIds } = data;
    let transaction;
    try {
      // 如果开启了事务, 数据库得操作都要放在同一个事务里面进行
      transaction = await ctx.model.transaction();
      await ctx.model.RoleRights.destroy({
        where: { roleId },
      });
      // 遍历出权限数组 然后逐个添加到表里面
      for (let i = 0; i < rightsIds.length; i++) {
        const obj = { roleId, rightsId: rightsIds[i] };
        await ctx.service.roleRights.create(obj);
      }
      await transaction.commit();
      ctx.success(data);
    } catch (e) {
      await transaction.rollback();
      ctx.error(400, e.message);
    }
  }

  // 移除角色的权限
  public async destroy() {
    const { ctx } = this;
    const { roleId } = ctx.params;
    const { rightsIds } = ctx.request.body;
    let transaction;
    try {
      transaction = await ctx.model.transaction();
      // 遍历出权限数组,然后逐个从表中删除
      for (let i = 0; i < rightsIds.length; i++) {
        await ctx.service.roleRights.destroy(roleId, rightsIds[i]);
      }
      await transaction.commit();
      ctx.success();
    } catch (e) {
      await transaction.rollback();
      ctx.error(400, e.message);
    }
  }
}
